package com.ly.heart.service.king.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.heart.domain.KingBaseBusinessGroupDetailEntity;
import com.ly.heart.domain.KingBaseBusinessGroupEntity;
import com.ly.heart.domain.KingBaseContactsEntity;
import com.ly.heart.domain.KingOrgEntity;
import com.ly.heart.domain.king.BaseChildBo;
import com.ly.heart.domain.king.base.businessGroup.BusinessGroupBo;
import com.ly.heart.domain.king.base.businessGroup.BusinessGroupFEntityBo;
import com.ly.heart.domain.king.base.contacts.ContactsBo;
import com.ly.heart.domain.king.order.FConfirmerIdBo;
import com.ly.heart.domain.king.order.OrderAuditBo;
import com.ly.heart.domain.king.order.OrderSubmitBo;
import com.ly.heart.domain.request.KingBaseSingleRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.service.IKingBaseBusinessGroupService;
import com.ly.heart.service.IKingBaseContactsService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 联系人推送Service
 */
@Component
@Slf4j
public class ContactsPushService {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd" );

    @Resource
    private IKingBaseContactsService baseContactsService;
    @Resource
    private IKingOrgService iKingOrgService;



    @Transactional( rollbackFor = Exception.class )
    public void push(String contactsId){
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity>().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity::getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        KingBaseContactsEntity kingBaseContactsEntity = baseContactsService.selectKingBaseContactsEntityById(contactsId);
        if(Objects.isNull(kingBaseContactsEntity)){
            throw new CustomException("联系人不存在！");
        }
        if(Objects.equals(kingBaseContactsEntity.getIsSend(), KingConstUtil.KING_DATA_IS_SEND_YES)){
            throw new CustomException("该联系人已推送金蝶,无需重复推送！");
        }
        try {
            K3CloudApi client = new K3CloudApi (identifyInfo);
            save(kingBaseContactsEntity,client);
            submit(kingBaseContactsEntity.getContactsCode(),client);
            audit(kingBaseContactsEntity.getContactsCode(),client);
            updateSendSuccess(contactsId);
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("推送联系人失败！");
        }
    }

    private void updateSendSuccess(String contactsId){
        KingBaseContactsEntity baseContactsEntity = new KingBaseContactsEntity();
        baseContactsEntity.setId(contactsId);
        baseContactsEntity.setIsSend(KingConstUtil.KING_DATA_IS_SEND_YES);
        baseContactsEntity.setChangeTime(DateUtils.getNowDate());
        baseContactsEntity.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        boolean flag = baseContactsService.updateById(baseContactsEntity);
        if(!flag){
            throw new CustomException("修改推送状态失败！");
        }
    }


    public void save(KingBaseContactsEntity businessGroupEntity, K3CloudApi client){
        try {
            String formId = KingConstUtil.BD_CommonContact;
            KingBaseSingleRequest singleRequest = new KingBaseSingleRequest ();
            ContactsBo contactsBo = this.assembleContactsBo(businessGroupEntity);
            singleRequest.setModel(contactsBo);
            //调用接口
            String resultJson = client.save(formId, JSONObject.toJSONString(singleRequest));
            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("联系人推送成功: {}", gson.toJson(repoRet.getResult()));
            } else {
                log.error("联系人推送失败: " + gson.toJson(repoRet.getResult().getResponseStatus()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void submit(String docCode, K3CloudApi client){
        try{
            OrderSubmitBo submitBo = new OrderSubmitBo();
            List<String> numbers = new ArrayList<>();
            numbers.add(docCode);
            submitBo.setNumbers(numbers);
            String formId = KingConstUtil.BD_CommonContact;
            String resultJson = client.submit(formId, JSON.toJSONString ( submitBo ));
            Gson gson = new Gson();
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("联系人提交成功: {}", gson.toJson(repoRet.getResult()));
            } else {
                log.error("联系人提交失败: {}",gson.toJson(repoRet.getResult().getResponseStatus()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void audit(String docCode,K3CloudApi client){
        try{
            OrderAuditBo auditBo = new OrderAuditBo();
            List<String> numbers = new ArrayList<>();
            numbers.add(docCode);
            auditBo.setNumbers(numbers);
            String formId = KingConstUtil.BD_CommonContact;
            String resultJson = client.audit(formId,JSON.toJSONString ( auditBo ));
            Gson gson = new Gson();
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
            if (baseResponse.getIsSuccess()) {
                log.info("联系人审核成功:{}", gson.toJson(repoRet.getResult()));
            } else {
                log.error("联系人审核失败:{}",gson.toJson(repoRet.getResult().getResponseStatus()) );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 联系人推送金蝶对象
     * @param baseContactsEntity
     * @return supplierBo
     */
    private ContactsBo assembleContactsBo(KingBaseContactsEntity baseContactsEntity){
        ContactsBo contactsBo = new ContactsBo();
        //联系人编码
        contactsBo.setFNumber(baseContactsEntity.getContactsCode());
        //姓名
        contactsBo.setFName(baseContactsEntity.getName());
        //性别
        if(StringUtils.isNotEmpty(baseContactsEntity.getSex())){
         String sex = baseContactsEntity.getSex().equals("0") ? "SEX01_SYS":"SEX02_SYS";
         BaseChildBo Fex = new BaseChildBo().setFNumber(sex);
         contactsBo.setFex(Fex);
        }
        //职务
        contactsBo.setFPost(baseContactsEntity.getPosition());
        //类型
        String type = baseContactsEntity.getType().equals("0") ? "BD_Supplier":"BD_Customer";
        contactsBo.setFCompanyType(type);
        //所属公司
        //固定电话
        contactsBo.setFTel(baseContactsEntity.getWorkTel());
        //移动电话
        contactsBo.setFMobile(baseContactsEntity.getMobile());
        //传真
        contactsBo.setFFax(baseContactsEntity.getFax());
        //邮箱
        contactsBo.setFEmail(baseContactsEntity.getEmail());
        //详细地址
        contactsBo.setFBizAddress(baseContactsEntity.getAddress());
        //地点名称
        contactsBo.setFBizLocation(baseContactsEntity.getAddressName());
        //地点编码
        contactsBo.setFBizLocNumber(baseContactsEntity.getAddressCode());
        //默认联系人
//        contactsBo.setFIsDefaultContact();
        return contactsBo;
    }






}
